package com.xac.common.util.io;

import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;


/**
 * 图片异步加载
 * 
 * @author frank
 * 
 */
public class AsyncImageLoader {

	/**
	 * 软引用对象，在响应内存需要时，由垃圾回收器决定是否清除此对象。软引用对象最常用于实现内存敏感的缓存。
	 */
	private HashMap<String, SoftReference<Drawable>> mImageCache = null;

	public AsyncImageLoader() {
		mImageCache = new HashMap<String, SoftReference<Drawable>>();
	}

	public Drawable loadDrawable(final String imageUrl, final ImageView imageView, final IImageCallback imageCallback) {
		if (mImageCache.containsKey(imageUrl)) {
			// 从缓存中读取
			Drawable drawable = mImageCache.get(imageUrl).get();
			if (drawable != null) {
				return drawable;
			}
		} else {
			final Handler handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					super.handleMessage(msg);
					imageCallback.loadImage((Drawable) msg.obj, imageView, imageUrl);
				}
			};
			new Thread() {
				public void run() {
					Drawable drawable = loadImageFromUrl(imageUrl);
					mImageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
					Message message = handler.obtainMessage(0, drawable);
					handler.sendMessage(message);
				}
			}.start();
		}
		return null;
	}

	public static Drawable loadImageFromUrl(String urlPath) {
		InputStream is = null;
		try {
			HttpURLConnection conn = (HttpURLConnection) new URL(urlPath).openConnection();
			is = conn.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Drawable drawable = Drawable.createFromStream(is, "src");
		is = null;
		return drawable;
	}

	/**
	 * 加载图片接口
	 * 
	 * @version 2011-11-15
	 */
	interface IImageCallback {

		public void loadImage(Drawable imageDrawable, ImageView imageView, String imageUrl);

	}

}
